package yongxin.controller.processreport;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jeecgframework.core.util.ResourceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

import yongxin.entity.annealer.AnnealerEntity;
import yongxin.entity.notice.NoticeEntity;
import yongxin.entity.process.ProcessEntity;
import yongxin.entity.processreport.ProcessReportEntity;
import yongxin.entity.workshop.WorkshopEntity;
import yongxin.service.process.ProcessServiceI;
import yongxin.service.processreport.ProcessReportServiceI;
import yongxin.service.workshop.WorkshopServiceI;

/**   
 * @Title: Controller
 * @Description: 工序汇报
 * @author zhangdaihao
 * @date 2015-02-05 14:03:13
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("/processReport004Controller")
public class ProcessReport004Controller extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ProcessReport004Controller.class);

	@Autowired
	private ProcessReportServiceI processReportService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private ProcessServiceI processService;
	 @Autowired
     private WorkshopServiceI workshopService;
	
	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * 工序汇报列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "processReport")
	public ModelAndView processReport(HttpServletRequest request) {
		String process=request.getParameter("process");
		request.setAttribute("process", process);
		if(process.equals("p4")){
			return new ModelAndView("yongxin/process/processReportList_p4");
		}
		else{
			return new ModelAndView("yongxin/process/processReportList");
		}
		
		
		
	}

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(ProcessReportEntity processReport,HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		
		String process=request.getParameter("process");
		CriteriaQuery cq = new CriteriaQuery(ProcessReportEntity.class, dataGrid);
		//查询条件组装器
		cq.eq("cprocess", process);
		if(StringUtil.isEmpty(processReport.getFstate())){
		cq.in("fstate", new Object[] { "0", "1" });
		}
		TSUser user = ResourceUtil.getSessionUser();//(TSUser) request.getSession().getAttribute("loginUser");
		if (user.getUserName().contains("bxg"))
		{
			cq.like("fbcph", "S%");
			
		} else if (user.getUserName().contains("tg"))
		{
			cq.like("fbcph", "Y%");
		}
		org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, processReport, request.getParameterMap());
		this.systemService.getDataGridReturn(cq, true);
		//String total_trzl = String.valueOf(processService.findOneForJdbc("select sum(CONVERT(numeric(19,2),ftrzl)) sum_trzl from t_processreport where fbcph = 'p4' and fstate in('0','1')").get("sum_trzl"));
		//total_trzl = total_trzl == "null"?"":total_trzl;
		dataGrid.setFooter("ftrkd:合计,ftrzl");
		TagUtil.datagrid(response, dataGrid);
		
	}

	/**
	 * 删除工序汇报
	 * 
	 * @return
	 */
	@RequestMapping(params = "del")
	@ResponseBody
	public AjaxJson del(ProcessReportEntity processReport, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		processReport = systemService.getEntity(ProcessReportEntity.class, processReport.getId());
		message = "工序汇报删除成功";
		processReportService.delete(processReport);
		systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
		
		j.setMsg(message);
		return j;
	}


	/**
	 * 添加工序汇报
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "save")
	@ResponseBody
	public AjaxJson save(ProcessReportEntity processReport,AnnealerEntity annealer,HttpServletRequest request) {

		AjaxJson j = new AjaxJson();

		if(StringUtil.isNotEmpty(processReport.getId())){
			message = "装炉成功";
			annealer.setFhbid(processReport.getId());
			annealer.setFstate("1");
			annealer.setFnote("");
			systemService.save(annealer);
			
			String[] ids = processReport.getId().split(",");
			for(int i = 0;i < ids.length;i++){
				ProcessReportEntity t = processReportService.get(ProcessReportEntity.class,ids[i]);
				t.setFmatchinegroup(annealer.getFmatchinegroup());
				t.setFworkgroup(annealer.getFworkgroup());
				t.setFworkshop(annealer.getFworkshop());
				t.setFstate("4");
				processReportService.saveOrUpdate(t);
			}
			
			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}
		
		
		
		
		j.setMsg(message);
		return j;
	}
    
	/**
	 * 
	 * 卸炉
	 * @param annealer
	 * @param request
	 * @return
	 */
	
	@RequestMapping(params = "returnReport2")
	@ResponseBody
	public AjaxJson returnReport2(AnnealerEntity annealer,HttpServletRequest request) {
		
		AjaxJson j = new AjaxJson();
		
		//获取炉id、 汇报id
		String id = request.getParameter("id");
		String fhbids = request.getParameter("fhbid");
		
		String[] fhbid = {fhbids};
		
		if(fhbids.contains(",")){
			 fhbid = fhbids.split(",");
		}
		
		String sql = " update t_processreport set fstate = '0' where id = ? ";   
		
		for(int i = 0;i < fhbid.length;i++){
			
			systemService.executeSql(sql, fhbid[i]);    // 更改炉内卷号状态
			
		}
		
		String sql2 = " delete from t_temp_record where flid = ? " ;
		systemService.executeSql(sql2, id);  // 删除温度记录
		systemService.deleteEntityById(AnnealerEntity.class, id);  // 删除炉子记录
		
	    message = "卸炉成功";
	    
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 工序汇报列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "addorupdate")
	public ModelAndView addorupdate(ProcessReportEntity processReport, HttpServletRequest req) {
		
		String ids=req.getParameter("ids");
		List<WorkshopEntity> workshopList = workshopService.findWorkshopList();
		req.setAttribute("workshopList", workshopList);
		
		List<ProcessReportEntity> list=new ArrayList<ProcessReportEntity>();
		if (StringUtil.isNotEmpty(ids)) {
			String[] id_s=ids.split(",");
			for (String id : id_s) {
				processReport = processReportService.getEntity(ProcessReportEntity.class, id);
				list.add(processReport);
			}
			
			req.setAttribute("processReportPage", list.get(0));
			req.setAttribute("processReportList", list);
		}
		else{
			if (StringUtil.isNotEmpty(processReport.getId())) {
				processReport = processReportService.getEntity(ProcessReportEntity.class, processReport.getId());
				req.setAttribute("processReportPage", processReport);
			}
		}
		/*else{
			String sql="select '' fid,tt.fbcph,tt.fworkshop,'' fmatchinegroup ,'' fworkgroup ,tt.ftype ftrgg,tt.fweight ftrzl, ";
			sql += " '' fccgg,'' fcczl,'' fbfzl,'' frate ,'' fnote,'' fcreatetime,'' fcreater ";
			sql += " from t_tasks tt ";
			sql += " inner join ( ";
			sql += " select * from t_process where fprocess='002') tp ";
			sql += " on tt.fbcph=tp.fbcph where tt.fbcph='20150205001' ";

			 List<Map<String,Object>> maplist=null;
			 try{
				 maplist=systemService.findForJdbc(sql, null);
			 }
			 catch(Exception ex){
				 
			 }
			 finally{
				 req.setAttribute("processReportPage", maplist);
			 }
		}*/
		if(processReport.getCprocess().equals("p4")){
			return new ModelAndView("yongxin/process/processReport_p4");
		}
		else{
			return new ModelAndView("yongxin/process/processReport");
		}
		
	}
	
	
	
	/**
	 * 添加工序汇报
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "getProcess")
	@ResponseBody
	public AjaxJson getProcess(ProcessReportEntity processReport, HttpServletRequest request) {
	
		
		String fbcph=request.getParameter("fbcph");
		String ofbcph="";
		if(fbcph!=null && fbcph.indexOf("-")>0){
			ofbcph=fbcph.substring(0,fbcph.indexOf("-"));
		}
		Object[] object=new Object[2];
		object[0]=fbcph;
		object[1]=ofbcph;
		
		
		String sql="select tp.fbcph,tp.fprocess,tp.create_date,dic.typename from t_process tp ";
		sql +=" left join (select tst.typecode,tst.typename from t_s_type tst,t_s_typegroup tstg ";
		sql +=" where tst.typegroupid=tstg.ID ";
		sql +=" and tstg.typegroupcode='ccgx') dic ";
		sql +=" on tp.fprocess=dic.typecode ";
		sql +=" where fbcph=? or fbcph=? ";
		sql +=" order by tp.create_date ";
		
		
		String sql2="select tst.typecode,tst.typename from t_s_type tst,t_s_typegroup tstg ";
		sql2 +=" where tst.typegroupid=tstg.ID ";
		sql2 +=" and tstg.typegroupcode='ccgx'";
		
		List<Map<String,Object>> maplist=null;
		List<Map<String,Object>> maplist2=null;
		 try{
			 maplist=systemService.findForJdbc(sql, object);
			 maplist2=systemService.findForJdbc(sql2,null);
		 }
		 catch(Exception ex){
			 
		 }
		 finally{
			
		 }
		 AjaxJson j = new AjaxJson();
		 j.setObj(maplist);
		 j.setMsg(createSelecte(maplist2));
		 
		return j;
	}
	
	private String createSelecte(List<Map<String,Object>> maplist){
		String select="<select id='nprocess' name='nprocess'><option value=''>请选择</option>";
		for (Map<String, Object> map : maplist) {
			select +="<option value="+map.get("typecode")+">"+map.get("typename")+"</option>";
		}
		select = select.replaceAll(select.substring(67,98), "");
		return select;
	}
	
	
}
